import React, { useState, useEffect, useRef } from 'react'
import { Button, Input, Badge, Steps, Table, message, InputNumber } from 'antd';
import './comm.css'
import { http, validators, UdPage, UdPageHeader, columnRenders } from '@/lib';
import apis from '@/apis/AboutQuota';
import MultiSelect from '@/pages/QuotaManage/GmApproval/multiSelect';
import { EDealerType } from '@/pages/QuotaManage/AdjustTheRecord/List';

const { Step } = Steps;
const deleteimg = require('@/assets/delete.png')
const setFlowReqVos = []
const Secondary = (props) => {
  const [dataSource, setDataSource] = useState([])
  const [inputValue, setinputValue] = useState([])
  const [inputRemark, setInputRemark] = useState([])
  const [CanNumValue, setCanNumValue] = useState([])
  const [template, setTemplate] = useState([])
  const [person, setPerson] = useState([])
  const [currentSelectPerson, setCurrentSelectPerson] = useState(-1)
  const childRef: any = useRef();

  const columns = [
    { title: '序号', key: 'id', dataIndex: 'id', render: (text, reoden, index) => index + 1 },
    { title: '客户名称', key: 'dealerName', dataIndex: 'dealerName' },
    { title: '客户类型', key: 'dealerType', dataIndex: 'dealerType', render: columnRenders.enum(EDealerType) },
    { title: '物料分类名称', key: 'groupName', dataIndex: 'groupName' },
    {
      title: '配额数量/件', key: 'quotaNum', dataIndex: 'quotaNum', width: 120,
      render: (text, rerocd, index) => {
        return <InputNumber
          defaultValue={text}
          onBlur={(e) => handelchange(e.target.value, index)}
          min={0} max={2 ** 31} maxLength={9} precision={0} style={{ width: 110 }}
        />
      }
    },
    { title: '已使用/件', key: 'quotaUseNum', dataIndex: 'quotaUseNum', width: 120 },
    {
      title: '可用/件', key: 'quotaCanNum', dataIndex: 'quotaCanNum', width: 120,
      render: (text, rerocd, index) => (
        <Input type="number" name={index}
          value={CanNumValue[index]}
          disabled
          placeholder={text}
          onChange={handelchangeCanNum}
        />)
    },
    { title: '开始日期', key: 'quotaStartTime', dataIndex: 'quotaStartTime' },
    { title: '结束日期', key: 'quotaEndTime', dataIndex: 'quotaEndTime' },
    {
      title: '状态', key: 'status', dataIndex: 'status', render: (text: number) => (
        <Badge
          status={text == 1 ? 'error' : 'success'}
          text={text == 1 ? '已过期' : '可使用'}
        />)
    },
    {
      title: '调整原因', key: 'remark', dataIndex: 'remark', width: 120,
      render: (text, rerocd, index) => {
        return (
          <Input
            defaultValue={text}
            onBlur={(e) => handelchangeRemark(e.target.value, index)}
            style={{ width: 110 }}
          />
        )
      }
    },
  ];
  const handelshowGM = (index) => { //审核model
    // childRef.current
    setCurrentSelectPerson(index)
    childRef.current.handelCeck(index)
  }
  useEffect(() => {
    let checkTale = sessionStorage.getItem('checkTable') || '[]'
    let data = JSON.parse(checkTale)
    setDataSource(dataSource.concat(data))
    getTemplete()
    return componentWillUnmount
  }, [])
  const handelDelite = (index: number, id: any) => {
    // let data = [...person]
    // data.splice(index, 1)
    // sessionStorage.setItem('person', JSON.stringify(person))
    let data = [...person]

    const curr = data[index].filter((a: any) => a.id !== id)

    data[index] = curr
    // data.splice(index, 1)
    sessionStorage.setItem('person', JSON.stringify(person))
    setPerson(data)
    setCurrentSelectPerson(index)
  }
  const Footerstyl = (props) => {
    return (
      <div style={{ width: 520 }}>
        <div className="Step_model">
          <Steps progressDot current={0} direction="vertical">
            {
              template.map((item, index) => (
                <Step key={index} title={item.name} />
              ))
            }
          </Steps>
          <div>
            {/* {
                    template.map((item,index)=>(
                      <div className="waper-check" key={index}>
                        {(item.assignee.slice(0,1)=='$'&& (!person[index] || !person[index].length ) )?
                          <div className="crli_model"  onClick={()=>handelshowGM(index)}>+</div>:
                          (item.assignee.slice(0,1)=='$'&&person.length!=0 && person[index])?person[index].map(resp=>(
                            <div className="crli_tname" key={resp.id}>
                              <img src={deleteimg}  className="deleteimg" onClick={()=>handelDelite(index)} />
                              {resp.realName}
                              </div>
                          )):
                          item.userNames?.map((res,idx)=>(
                          <div className="crli_tname" key={idx}>{res}</div>   
                          ))
                        }
                      </div>
                    ))
                  } */}
            {
              template.map((item, index) => (
                <div className="waper-check" key={index}>
                  {
                    person[index] && person[index].map((resp: any) => (
                      <div className="crli_tname" key={resp.id}>
                        <img src={deleteimg} className="deleteimg" onClick={() => handelDelite(index, resp.id)} />
                        {resp.realName}
                      </div>
                    ))
                  }
                  <div className="crli_model" onClick={() => handelshowGM(index)}>+</div>
                </div>
              ))
            }
          </div>
        </div>
        <div className="button-tj">
          <Button type="primary" onClick={props.handeltoSubmits} >提交审核</Button>
        </div>
      </div>
    )


  }
  const getTemplete = () => { //获取审批模板
    let brandCode = props.match.params.brandCode
    console.log(props);
    http.get(apis.adjustTemplate, { params: { brandCode } })
      .then(resp => {
        setTemplate(resp.data)
        let data = JSON.stringify(resp.data)
        sessionStorage.setItem('role', data)
      })
  }
  function componentWillUnmount() {
    // 组件销毁时执行的代码
    sessionStorage.removeItem('checkTable')
  }
  function handelchange(value, index) {
    let data = [...inputValue]
    let setdata = [...CanNumValue]
    data[index] = value
    //  setdata[index] = value - dataSource[index].quotaUseNum || 0
    // 配额调整后的可用数量 = 调整前可用数量（临时储存的originQuotaCanNum） - 原配额数量（临时储存的originQuotaNum） + 调整后的配额数量
    setdata[index] = (Number(dataSource[index].originQuotaCanNum || 0) - Number(dataSource[index].originQuotaNum || 0) + Number(value)) || 0
    setinputValue(data)
    setCanNumValue(setdata)
  }

  function handelchangeCanNum(e) {
    let data = [...CanNumValue]
    data[e.target.name] = e.target.value
    setCanNumValue(data)
  }

  function handelchangeRemark(value, index) {
    let data = [...inputRemark]
    data[index] = value
    setInputRemark(data)
  }

  const handelgetperson = (value) => {
    if (currentSelectPerson == -1) return

    let data = [...person]
    data[currentSelectPerson] = value
    sessionStorage.setItem('person', JSON.stringify(person))
    setPerson(data)
  }
  const handeltoSubmit = () => {
    let checkTable = sessionStorage.getItem('checkTable')
    let newData = JSON.parse(checkTable)
    let sameData = [...newData]

    if (sameData.length !== inputRemark.length || inputRemark.some((a: any) => !a)) return message.warning('请填写调整原因')

    let same = sameData.map((item, index) => {
      item.quotaNum = inputValue[index] || item.quotaNum
      item.quotaCanNum = CanNumValue[index] || item.quotaCanNum
      item.remark = inputRemark[index] || item.remark
      return item
    })
    let list = template.filter(item=>item.assignee.slice(0,1)=='$')
    if ((person.length != 0 && template.length != 0) || (person.length == 0 && template.length == 0)) {
      template.map((item, index) => {
        const user = person[index] || []
        setFlowReqVos.push({ name: item.assignee, userIds: user.map((a: any) => a.id) || [] })
      })
      const data = {
        quotaReqVoList: same,
        workflowReqVos: setFlowReqVos
      }
      http.put(apis.SubmitAudit, { ...data }).then(res => {
        message.success("提交成功！")
        window.history.go(-1)
      }).catch(() => {
        message.error("请填写调整的数量")
      })
    } else {
      message.warning("请选择审批人")
    }
  }

  return (
    <UdPage>
      <UdPageHeader title='配额调整' onBack={props.history.goBack} />
      <Table dataSource={dataSource} columns={columns} pagination={false} rowKey={redrod => redrod.id} />
      <div className="sp-text">审批流程：</div>
      <Footerstyl handeltoSubmits={handeltoSubmit} />
      <MultiSelect cRef={childRef} handelcilck={handelgetperson} />
    </UdPage>
  )

}




export default Secondary